<template>
  <el-form ref="form" :model="form" :rules="rules">
    <el-form-item :label="$t('user.password')" prop="password">
      <el-input
        ref="password"
        v-model="form.password"
        :type="passwordType"
        placeholder="Password"
      />
    </el-form-item>
    <el-form-item :label="$t('user.confirmPassword')" prop="confirmPassword">
      <el-input
        ref="confirmPassword"
        v-model="form.confirmPassword"
        :type="passwordType"
        placeholder="Confirm Password"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" :loading="loading" @click="onSubmit">Update</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { resetPassword } from '@/api/user'
export default {
  inject: ['reload'],
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('The password can not be less than 6 digits'))
      } else {
        callback()
      }
    }
    const checkConfirmPassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('The password can not be less than 6 digits'))
      } else if (value !== this.form.password) {
        callback(new Error('The passwords are inconsistent'))
      } else {
        callback()
      }
    }
    return {
      form: {
        password: '',
        confirmPassword: ''
      },
      rules: {
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        confirmPassword: [{ required: true, trigger: 'blur', validator: checkConfirmPassword }]
      },
      passwordType: 'password',
      loading: false
    }
  },
  methods: {
    onSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          resetPassword({
            password: this.form.password
          }).then(res => {
            this.$confirm('success', 'title', {
              confirmButtonText: 'ok',
              showCancelButton: false,
              type: 'success'
            }).then(() => {
              this.reload()
            })
            this.loading = false
          }).catch(err => {
            console.log(err)
            this.loading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>
